package com.wgo.bpot.server.persist.trigger;

import java.util.HashSet;
import java.util.Set;

import com.wgo.bpot.domain.common.CrudOperation;
import com.wgo.bpot.server.persist.PersistService;


public class TriggerRegistryImpl implements TriggerRegistry {
	private PersistService persistService;
	private Set<Trigger> triggers = new HashSet<Trigger>();

	public TriggerRegistryImpl(PersistService persistService) {
		this.persistService = persistService;
	}
	
	/* (non-Javadoc)
	 * @see com.wgo.bpot.server.persist.trigger.TriggerRegistry#invokeBefore(com.wgo.bpot.server.persist.trigger.CrudOperation, java.lang.Object)
	 */
	public void invokeBefore(CrudOperation operation,Object triggerTarget){
		invokeTrigger(operation,true,triggerTarget);
	}
	 
	/* (non-Javadoc)
	 * @see com.wgo.bpot.server.persist.trigger.TriggerRegistry#invokeAfter(com.wgo.bpot.server.persist.trigger.CrudOperation, java.lang.Object)
	 */
	public void invokeAfter(CrudOperation operation,Object triggerTarget){
		invokeTrigger(operation,false,triggerTarget);
	}
	 
	private void invokeTrigger(CrudOperation operation,boolean isBefore, Object triggerTarget){
		for (Trigger trigger : triggers) {
			if (trigger.isApplicable(operation) && trigger.isApplicable(triggerTarget) && (trigger.isBefore() == isBefore)) {
				trigger.trigger(triggerTarget);
			}
		}
	}

	/* (non-Javadoc)
	 * @see com.wgo.bpot.server.persist.trigger.TriggerRegistry#addTrigger(com.wgo.bpot.server.persist.trigger.Trigger)
	 */
	public void addTrigger(Trigger trigger){
		triggers.add(trigger);
		trigger.setPersistService(persistService);
	}

	/* (non-Javadoc)
	 * @see com.wgo.bpot.server.persist.trigger.TriggerRegistry#removeTrigger(com.wgo.bpot.server.persist.trigger.Trigger)
	 */
	public void removeTrigger(Trigger trigger){
		triggers.remove(trigger);
	}
	
	public void setTriggers(Set<Trigger> triggers) {
		this.triggers = triggers;
	}
	
}
